import React from 'react';
import { ProgressHorizonProps } from './interface';
import './index.less';

const defaultProps: ProgressHorizonProps = {
  percent: 0,
  color: '#7ed321',
  backgroundColor: 'rgba(9, 59, 59, 0.7)',
  isRadius: false,
};

/**
 * 渐变进度条
 * @author hupeng
 * @datetime 2021-3-23 22:02
 */
const ProgressHorizon: React.FC<ProgressHorizonProps> & {
  defaultProps: Partial<ProgressHorizonProps>;
} = props => {
  const { style, percent, color, backgroundColor, isRadius } = props;
  let num = 0;
  let borderRadius = 0;

  if (percent) {
    num = percent;
  }

  if (num > 100) {
    num = 100;
  }

  let bg = '';

  if (typeof color === 'string') {
    bg = color;
  } else {
    const colorLi = [];

    if (color && color.length > 0) {
      const len = color.length;
      const interval = 100 / (len - 1); // 计算每个点的间隔
      const colorTmp = []; // 存储当前进度的颜色值

      for (let i = 0; i < len; i += 1) {
        colorTmp.push(color[i]);
        if (i * interval > num) {
          break;
        }
      }

      const len1 = colorTmp.length;
      const interval1 = 100 / (len1 - 1);

      for (let i = 0; i < len1; i += 1) {
        colorLi.push(`${colorTmp[i]} ${i * interval1}%`);
      }
    } else {
      colorLi.push('#7ed3217f 0%');
      colorLi.push('#7ed321ff 100%');
    }

    bg = `linear-gradient(to right, ${colorLi.join(',')})`;
  }

  if (isRadius) {
    borderRadius = 4;
    if (style && style.height) {
      borderRadius = Number(style.height) / 2;
    }
  }

  return (
    <div className="dv-progress-horizon" style={style}>
      <div
        className="progress-bar-bg"
        style={{ backgroundColor, borderRadius }}
      >
        <div
          className="progress-bar-in"
          style={{ width: `${num}%`, background: bg, borderRadius }}
        >
          <div className="progress-bar-animation" style={{ borderRadius }} />
        </div>
      </div>
    </div>
  );
};

ProgressHorizon.defaultProps = defaultProps;

export default ProgressHorizon;
